var express = require('express');
var router = express.Router();
// 引入文件上传模块
var multiparty = require('multiparty')
// 引入加密模块
var crypto = require('crypto')
var { UserModel,  HeadlineModel, ZhiFuModel, ReviewModel,
  TravelPlanModel, ScenicSpotModel } = require('../model/models');
// 引入阿里云短信发送模块
const SMSClient = require('@alicloud/sms-sdk');
let smsCode = Math.random().toString().slice(-6);
// 引入jwt模块
var jwt = require("jsonwebtoken")
// // 引入支付模块
// let AlipaySdK = require('alipay-sdk').default;
// let AlipaySdkForm = require('alipay-sdk/lib/form').default;
// 引入腾讯人脸识别包
const tencentcloud = require('tencentcloud-sdk-nodejs-iai');
//注册接口
router.post("/registor", (req, res) => {
  let { username, password } = req.body
  //对密码进行加密处理
  //生成加密对象
  let hash = crypto.createHash('md5')
  //使用加密对象进行加密并生成十六进制字符串
  let newpwd = hash.update(password).digest('hex')
  UserModel.create({username,password:newpwd})
  res.send({
    code: 200,
    msg: "注册成功"
  })
})
// 登录接口
router.post("/login", async (req, res) => {
  let { user, password, email } = req.body
  let hash = crypto.createHash('md5')
   //使用加密对象进行加密并生成十六进制字符串
  let newPwd = hash.update(password).digest('hex')
  if (user != "") {
    let userInfo = await UserModel.findOne({ username: user, password:newPwd })
    if (userInfo) {
      let token=jwt.sign({user:userInfo.username},'123456',{expiresIn:'1h'})
      res.send({ code: 200, msg: "登录成功", data: userInfo,token })
    } else {
      res.send({ code: 400, msg: "用户名或密码错误" })
    }
  }
  if (email != "") {
    let emailInfo = await UserModel.findOne({ email, password:newPwd })
    if (emailInfo) {
      res.send({ code: 200, msg: "登录成功", data: emailInfo })
    } else {
      res.send({ code: 400, msg: "邮箱或密码错误" })
    }
  }
})
// 六位验证码
function getCode() {
  let str = "";
  for (let i = 0; i < 6; i++) {
    str += parseInt(Math.random() * 10)
  }
  return str;
}
// 发送短信
let msm = ''
router.post('/sendSms', async (req, res) => {
  //获取前端参数phone参数
  let phoneNum = req.body.phone;
  console.log("手机号码", phoneNum);
  //初始化sms_client
  let smsClient = new SMSClient({
    accessKeyId: 'LTAI5tDwhj4aqQoecxx5BrP8',  //accessKeyId 前面提到要准备的
    secretAccessKey: 'B7vKUSfttlZQWOLKDTOhOx7nTYMkzp'  //secretAccessKey 前面提到要准备的
  });
  let str = getCode();
  console.log(str);
  
  msm = str;
  // 开始发送短信
  smsClient.sendSMS({
    PhoneNumbers: phoneNum,
    SignName: "凤凰旅游", //签名名称 前面提到要准备的
    TemplateCode: "SMS_475935698        ", //模版CODE  前面提到要准备的
    TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
  }).then(result => {
    console.log("result", result)
    let { Code } = result;
    if (Code == 'OK') {
      res.json({
        code: 0,
        msg: 'success',
        sms: str
      })
      console.log(result)
    }

    
  }).catch(err => {
    console.log(err);
    res.json({
      code: 1,
      msg: 'fail: ' + err.data.Message
    })
  })
})
//手机号登录
router.post('/login_phone', async (req, res) => {
  let { phone, yanzhengma } = req.body

  console.log(yanzhengma,msm);
  
  if (yanzhengma == msm) {
 
    let user = await UserModel.findOne({ phone:phone})
    console.log(user);
    if (user) {
      let token = jwt.sign({ username: user.username }, 'secret', { expiresIn: '1h' }) //生成token
      res.json({
        code: 0,
        msg: 'success',
        token: token
      }
      )
    } else {
      res.json({
        code: 1,
        msg: '用户不存在'
      })
    }
  }
});
//人脸识别登录
router.post('/faceLogin', async (req, res) => {
  //获取前端传来的base64
  let imageData = req.body.imageData
  // console.log(imageData);

  const IaiClient = tencentcloud.iai.v20200303.Client;
  const clientConfig = {
    credential: {
      //腾讯secretId
      secretId: "AKIDrbAXkkakgPgldLp8KPGvOflgMuJ2e7Th ",
      //腾讯密匙
      secretKey: "CB0gBSWQ8cw2JODrGUAgz52omhfdUAcv",
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.ap-beijing.tencentcloudapi.com",
      },
    },
  };

  const client = new IaiClient(clientConfig);

  const params = {
    "GroupIds": [  //你创建的人员库ID
      "2024001"
    ],
    "Image": imageData,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };

  let doc = await client.SearchFaces(params)

  //doc为人脸识别后的返回信息
  // console.log(doc, 'doc');


  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    console.log(personName, 'personName');

    let resident = await UserModel.findOne({ username: personName })

    res.send({
      code: 200,
      msg: "登录成功！",
      id: resident._id
    })
  } else {
    res.send({
      code: 401,
      msg: '人脸库无此人！'
    })
    return false
  }
})
//获取景区数据
router.get('/jingqu', async (req, res) => {
  let data = await ScenicSpotModel.find();
  let { grade } = req.query
  if (grade) {
    data = data.filter(item => item.grade === grade)
  }
  res.send({
    code: 200,
    data
  })
})
//获取景区详情
//景区详情页
router.get('/jingquxiangqing',async (req,res)=>{
    let {_id} = req.query
    console.log(_id);
    
    let data = await ScenicSpotModel.find({_id});
    res.send({
      code:200,
      data
    })
  })
  //支付订单添加
  router.post('/addZhiFu',(req,res)=>{
    let {name,price,people,num,type} = req.body
    ZhiFuModel.create({name,price,people,num,type})
    res.send({
      code:200,
      msg:'添加成功'
    })
  })
  // 引入支付模块
let AlipaySdK = require('alipay-sdk').default;
let AlipaySdkForm = require('alipay-sdk/lib/form').default;

router.post('/alipay',async(req,res)=>{
  let {name,price} = req.body //获取前端传递过来的参数
	//创建客户端配置信息
	const alipaySdk = new AlipaySdK({
		// 设置应用 ID
		appId: '9021000142606258',
		gateway:'https://openapi-sandbox.dl.alipaydev.com/gateway.do',//支付网关
		
		// 设置应用私钥
		privateKey:"MIIEowIBAAKCAQEAgzhU431xYg3cii/4muwegfHAgWfR9SYC79BZLpEmkiy5S/pr2DOxhOrOt9J21v14pjGDIOriSPaWmy37HMw5isgqiDu1oli//ANwr/1y0UU3XXpXqINpTLZ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ydIGruulRRHFTZcVkSDNeszQ5BCQQKBgGplAjyyE902vUJCLwC2ox3K7rV50n1hjjsXlsdI7uJ/rh964wiqIERj+TWPgklVC5VkpiO+HJ7TMVVC3uHfifWUbUat5r8GrCwDjGKW1wIaDM/KZGHJwKsfBtrbwnFtVhG7y2rqiFsM8pElkczeW0mXgN60r4TIElveSNchlIwnAoGBAObtR2WO3tkunEw1Bq+zO6aZ9H7dxA36odhCklEHNKT5ZuondQHhkHNKrvb608OVouWPxHHyttn6avY0qsurHHeZ8xrwyTgdph/EmouH0c5/yB+z3sx+c8BzkT++4FNznxMB2TnxJLXw81aI4a/wFiGXnfGQnzFU/E2ta8MipX4S",
		// 设置支付宝公钥
		alipayPublicKey:"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkcCkv3GWA1OpvUNK6lU4MdUHNqOSiCB98yep3gbOd2aZMx/+v0lBsD2dRqTpMunxLv41rhChjxUG4/5kgdI8Wq0yAJf+3g5gPmkePtlqQepr60KB9RLIR8vlRoFbcjlx0Zm6bYj0gMBWb0B5N/OHMv9NOMcShy/zJeCpMndj0TDwmAfObTzFa6WDrSWJiN8FomKKb7y3JvlILpOsVQibse4JCeeko5S3D8BYsu4eagpYfCOsCWqUEKpVBFcKwUAMd+q7+NRin0u0DQ6JgALm5/vKYjBDrwAwpoYUdnkEDYR5lMRZeSTW1YIODjrLqRvnxP+mUAdAmesdWUpH+dpfowIDAQAB",
		// 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
		// keyType: 'PKCS1',
		// 设置网关地址，默认是 https://openapi.alipay.com
		// endpoint: 'https://openapi.alipay.com',
		signType:'RSA2',//注意这里默认RSA2，正常不需要配置
	  });
	let formData = new AlipaySdkForm();
	formData.addField('returnUrl','http://localhost:3001/shou/index')//支付成功后跳转的地址
	formData.addField('bizContent',{
		outTradeNo:Date.now(),//订单号
		productCode:'FAST_INSTANT_TRADE_PAY',//销售产品码，与支付宝签约的产品码名称。注：目前仅支持FAST_INSTANT_TRADE_PAY
		totalAmount:price,//金额
		subject:name,
		body:name
	});
	//请求第三方接口
	const result = await alipaySdk.exec(
		'alipay.trade.wap.pay',//支付类型  wap.pay-H5端支付  page.pay-PC端支付
		{},
		{formData:formData},
	);
	// console.log(result,'result');
	res.send(result)
})
// 获取文旅头条
router.get('/toutiao', async (req, res) => {
  let tou = await HeadlineModel.find();
  res.send({
    code: 200,
    tou
  })
})
// 图片上传接口
router.post('/imgurl',(req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = 'uploads';
  form.parse(req, (err, fields, files) => {
    console.log(files);
    
    res.send({
      // path:'http://127.0.0.1:3001/'+files['file'][0].path
      code:200
    })
  });
})
// 获取旅游计划
router.get('/travellist',async(req,res)=>{
  let travelist = await TravelPlanModel.find()
  console.log(travelist);
  
  res.send({
    travelist
  })
})
// 添加旅游计划
router.post('/traveladd',(req,res)=>{

TravelPlanModel.create(req.body)
res.send({
  code:200,
  msg:'添加成功'
})
})
// 删除旅游计划
router.post('/deltravel',async(req,res)=>{
let {id} = req.query
await TravelPlanModel.deleteOne({_id:id})
console.log(id);

res.send({
  code:200,
  msg:'删除成功'
})
})
module.exports = router;
